import 'package:flutter/material.dart';

import '../container/separated_row.dart';

/// FileName public_grid_view
///
/// @Author lax
/// @Date 2025/3/3
///
/// @Description

class PublicGridView extends StatelessWidget {
  final int itemCount;
  final NullableIndexedWidgetBuilder itemBuilder;

  final int crossAxisCount;

  final double crossAxisSpacing;
  final double mainAxisSpacing;

  final MainAxisAlignment? mainAxisAlignment;
  final CrossAxisAlignment? crossAxisAlignment;

  final EdgeInsets? margin;
  final EdgeInsets? padding;

  final bool shrinkWrap;
  final ScrollPhysics? physics;

  final bool expanded;

  const PublicGridView({
    super.key,
    required this.itemCount,
    required this.itemBuilder,
    this.crossAxisCount = 1,
    this.crossAxisSpacing = 0,
    this.mainAxisSpacing = 0,
    this.mainAxisAlignment,
    this.crossAxisAlignment,
    this.margin,
    this.padding,
    this.shrinkWrap = false,
    this.physics = const AlwaysScrollableScrollPhysics(),
    this.expanded = true,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: margin ?? EdgeInsets.zero,
      child: ListView.separated(
        padding: padding ?? EdgeInsets.zero,
        shrinkWrap: shrinkWrap,
        physics: physics,
        itemCount: (itemCount / crossAxisCount).ceil(),
        itemBuilder: (context, index) {
          List<Widget> children = [];
          for (int i = 0; i < crossAxisCount; i++) {
            if (itemCount > (index * crossAxisCount + i)) {
              children.add(itemBuilder(context, index * crossAxisCount + i) ??
                  const SizedBox());
            } else {
              children.add(const SizedBox());
            }
          }
          return SeparatedRow(
            mainAxisAlignment: mainAxisAlignment,
            crossAxisAlignment: crossAxisAlignment,
            separator: SizedBox(width: crossAxisSpacing),
            expanded: expanded,
            children: children,
          );
        },
        separatorBuilder: (_, index) {
          return SizedBox(height: mainAxisSpacing);
        },
      ),
    );
  }
}
